package com.yoomiito.app.ui.anyview.material

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.text.TextUtils
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.app.ActivityCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.google.android.material.tabs.TabLayout
import com.scwang.smartrefresh.header.MaterialHeader
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.footer.ClassicsFooter
import com.umeng.socialize.bean.SHARE_MEDIA
import com.yoomiito.app.*
import com.yoomiito.app.adapter.material.MaterialAdapter
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.BaseList
import com.yoomiito.app.model.MaterialContent
import com.yoomiito.app.model.MaterialLabel
import com.yoomiito.app.model.ViewType
import com.yoomiito.app.utils.*
import com.yoomiito.app.utils.wx.ShareUtils
import com.yoomiito.app.utils.wx.UMengShareUtils
import com.yoomiito.app.utils.wx.WXUtils
import com.yoomiito.app.widget.SpacingDecoration
import com.yoomiito.app.widget.dialog.CustomDialog1
import com.yoomiito.app.widget.dialog.ShareBottomDialog_1
import com.yoomiito.app.widget.dialog.ShareDialog
import com.yoomiito.app.widget.state.ContentType
import com.yoomiito.app.widget.state.EmptyType
import com.yoomiito.app.widget.state.StatusManager

class MaterialView(val mContext: Context) : LinearLayout(mContext) {

    private var mTabLayout: TabLayout? = null
    private var mSmartRefreshLayout: SmartRefreshLayout? = null
    private var mRcy: androidx.recyclerview.widget.RecyclerView? = null
    private val shareDialog: ShareBottomDialog_1 by lazy { ShareBottomDialog_1(mContext) }
    private val shareGuidDialog: ShareDialog by lazy { ShareDialog(mContext) }
    private val datas = mutableListOf<ViewType<MaterialContent>>()
    private var mCustomDialog : CustomDialog1 ? = null
    private val materialAdapter = MaterialAdapter(mContext, datas)
    var OnRefreshListener: (Int, Long) -> Unit = { _, _ -> }
    private var labels: List<MaterialLabel>? = null
    private val mStatusManager = StatusManager.Builder(mContext)
            .addType(ContentType(R.layout.refresh_rcy_layout))
            .addType(EmptyType(R.layout.item_empty_1).setShowViewListener {
                val iv = it.findViewById<ImageView>(R.id.bg_empty)
                val lp = iv.layoutParams as LinearLayout.LayoutParams
                lp.topMargin = DensityUtil.dp2px(83f)
            })
            .build()

    init {

        addView(LayoutInflater.from(mContext).inflate(R.layout.view_material, this, false))
        mTabLayout = findViewById(R.id.tabLayout)
        mTabLayout?.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(p0: TabLayout.Tab?) {
            }

            override fun onTabUnselected(p0: TabLayout.Tab?) {
            }

            override fun onTabSelected(p0: TabLayout.Tab?) {
                mSmartRefreshLayout?.setNoMoreData(false)
                OnRefreshListener(3, labels?.get(p0?.position!!)?.id!!)
            }

        })
        val frameLayout = findViewById<FrameLayout>(R.id.frameLayout)
        frameLayout.addView(mStatusManager.view())
        mSmartRefreshLayout = findViewById(R.id.refreshLayout)
        mSmartRefreshLayout?.setRefreshHeader(MaterialHeader(mContext))
        mSmartRefreshLayout?.setRefreshFooter(ClassicsFooter(mContext))
        mSmartRefreshLayout?.setOnRefreshListener {
            OnRefreshListener(1, -1)
        }
        mSmartRefreshLayout?.setOnLoadMoreListener {
            OnRefreshListener(2, -1)
        }
        mRcy = findViewById(R.id.rcy)
        mRcy?.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(mContext)
        mRcy?.addItemDecoration(SpacingDecoration(0, DensityUtil.dp2px(10f), false))
        mRcy?.adapter = materialAdapter
        materialAdapter.OnShareClickListener = {
            if (App.mAppConfig.isLogin) {
                showShareDialog(it)
            } else {
                LoginUtils.toOneKeyLogin(mContext as BaseActivity<*>)
            }
        }
    }

    fun showLabel(labels: List<MaterialLabel>?) {
        this.labels = labels
        mTabLayout?.removeAllTabs()
        labels?.forEach {
            mTabLayout?.addTab(mTabLayout?.newTab()?.setText(it.label)!!)
        }
    }

    fun showList(data: BaseList<MaterialContent>?) {
        if (data?.current_page!! >= data?.last_page) {
            mSmartRefreshLayout?.finishLoadMoreWithNoMoreData()
        }
        mSmartRefreshLayout?.finishRefresh()
        mSmartRefreshLayout?.finishLoadMore()
        if (data?.current_page == 1) {
            datas.clear()
            if (data == null || data.data==null || data.data.size == 0) {
                mStatusManager.showEmpty()
                return
            }
            mStatusManager.showContent()
        }

        data?.data?.forEach {
            datas.add(ViewType(//1 图 2 视频 3 文字
                    when {
                        it.type == 1 && it.img.size > 1 -> Type.MaterialType.TextMultiMap
                        it.type == 1 && it.img.size == 1 -> Type.MaterialType.TextSingleImage
                        it.type == 2 -> Type.MaterialType.TextVideo
                        else -> Type.MaterialType.Text
                    },
                    it)
            )
            materialAdapter.notifyDataSetChanged()
        }
    }

    private fun showShareDialog(info: ViewType<MaterialContent>) {
        val data = info.t
        data.content.copyClipboard(context)
        shareDialog.setOnShareItemClickListener { i ->
            when (i) {
                1 -> {
                    when (info.viewType) {
                        Type.MaterialType.Text -> {
                            UMengShareUtils.shareWXText(mContext as BaseActivity<*>, data.content)
                        }
                        Type.MaterialType.TextMultiMap -> {
//                            data.content.copyClipboard(context)
                            ShareUtils.shareWX(mContext as BaseActivity<*>, data.img, data.content)
                        }
                        Type.MaterialType.TextSingleImage -> {
//                            data.content.copyClipboard(context)
                            UMengShareUtils.shareWXPic(SHARE_MEDIA.WEIXIN, mContext as BaseActivity<*>, data.img[0])
                        }
                        Type.MaterialType.TextVideo -> {
//                            data.content.copyClipboard(context)
                            val permissions = arrayOf(
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                            )
                            var sb: StringBuilder? = null
                            for (permission in permissions) {
                                if (ActivityCompat.checkSelfPermission(
                                        mContext,
                                        permission!!
                                    ) != PackageManager.PERMISSION_GRANTED
                                ) {
                                    if (sb == null) {
                                        sb = StringBuilder()
                                    }
                                    val str = AllUtils.permissionTipMap(permission)
                                    if (sb.indexOf(str) == -1) {
                                        if (!TextUtils.isEmpty(sb)) {
                                            sb.append("\n\n")
                                        }
                                        sb.append(str)
                                    }
                                }
                            }
                            if (sb == null || TextUtils.isEmpty(sb)) {
                                data.video.saveVideoAndOpenWx(mContext as BaseActivity<*>)
                            } else {
                                if (mCustomDialog == null) {
                                    mCustomDialog = CustomDialog1(mContext,
                                        CustomDialog1.OnCloseListener {
                                            data.video.saveVideoAndOpenWx(mContext as BaseActivity<*>)
                                        })
                                }
                                mCustomDialog?.setContent(sb.toString())
                                mCustomDialog?.show()
                            }
                        }
                    }
                }//微信好友
                2 -> {
                    when (info.viewType) {
                        Type.MaterialType.Text -> {
//                            data.content.copyClipboard(context)
                            WXUtils.openWX(mContext)
                        }
                        Type.MaterialType.TextMultiMap -> {
//                            data.content.copyClipboard(context)
                            val permissions = arrayOf(
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                            )
                            var sb: StringBuilder? = null
                            for (permission in permissions) {
                                if (ActivityCompat.checkSelfPermission(
                                        mContext,
                                        permission!!
                                    ) != PackageManager.PERMISSION_GRANTED
                                ) {
                                    if (sb == null) {
                                        sb = StringBuilder()
                                    }
                                    val str = AllUtils.permissionTipMap(permission)
                                    if (sb.indexOf(str) == -1) {
                                        if (!TextUtils.isEmpty(sb)) {
                                            sb.append("\n\n")
                                        }
                                        sb.append(str)
                                    }
                                }
                            }
                            if (sb == null || TextUtils.isEmpty(sb)) {
                                AllUtils.requestPermission(mContext as BaseActivity<*>, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE)
                                    .subscribe { aBoolean ->
                                        if (data.img != null && data.img.size > 0) {
                                            ImageLoader.getInstance().downloadPic(mContext, data.img)
                                            shareGuidDialog.show()
                                        }
                                    }
                            } else {
                                if (mCustomDialog == null) {
                                    mCustomDialog = CustomDialog1(mContext,
                                        CustomDialog1.OnCloseListener {
                                            AllUtils.requestPermission(mContext as BaseActivity<*>, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                                Manifest.permission.READ_EXTERNAL_STORAGE)
                                                .subscribe { aBoolean ->
                                                    if (data.img != null && data.img.size > 0) {
                                                        ImageLoader.getInstance().downloadPic(mContext, data.img)
                                                        shareGuidDialog.show()
                                                    }
                                                }
                                        })
                                }
                                mCustomDialog?.setContent(sb.toString())
                                mCustomDialog?.show()
                            }
                        }
                        Type.MaterialType.TextSingleImage -> {
//                            data.content.copyClipboard(context)
                            UMengShareUtils.shareWXPic(SHARE_MEDIA.WEIXIN_CIRCLE, mContext as BaseActivity<*>, data.img[0])
                        }
                        Type.MaterialType.TextVideo -> {
//                            data.content.copyClipboard(context)

                            val permissions = arrayOf(
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                            )
                            var sb: StringBuilder? = null
                            for (permission in permissions) {
                                if (ActivityCompat.checkSelfPermission(
                                        mContext,
                                        permission!!
                                    ) != PackageManager.PERMISSION_GRANTED
                                ) {
                                    if (sb == null) {
                                        sb = StringBuilder()
                                    }
                                    val str = AllUtils.permissionTipMap(permission)
                                    if (sb.indexOf(str) == -1) {
                                        if (!TextUtils.isEmpty(sb)) {
                                            sb.append("\n\n")
                                        }
                                        sb.append(str)
                                    }
                                }
                            }
                            if (sb == null || TextUtils.isEmpty(sb)) {
                                data.video.saveVideoAndOpenWx(mContext as BaseActivity<*>)
                            } else {
                                if (mCustomDialog == null) {
                                    mCustomDialog = CustomDialog1(mContext,
                                        CustomDialog1.OnCloseListener {
                                            data.video.saveVideoAndOpenWx(mContext as BaseActivity<*>)
                                        })
                                }
                                mCustomDialog?.setContent(sb.toString())
                                mCustomDialog?.show()
                            }

                        }
                    }
                }//朋友圈
                3 -> {//保存相册
                    when (info.viewType) {
                        Type.MaterialType.TextMultiMap, Type.MaterialType.TextSingleImage -> {


                            val permissions = arrayOf(
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                            )
                            var sb: StringBuilder? = null
                            for (permission in permissions) {
                                if (ActivityCompat.checkSelfPermission(
                                        mContext,
                                        permission!!
                                    ) != PackageManager.PERMISSION_GRANTED
                                ) {
                                    if (sb == null) {
                                        sb = StringBuilder()
                                    }
                                    val str = AllUtils.permissionTipMap(permission)
                                    if (sb.indexOf(str) == -1) {
                                        if (!TextUtils.isEmpty(sb)) {
                                            sb.append("\n\n")
                                        }
                                        sb.append(str)
                                    }
                                }
                            }
                            if (sb == null || TextUtils.isEmpty(sb)) {
                                AllUtils.requestPermission(mContext as BaseActivity<*>, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE)
                                    .subscribe { aBoolean ->
//                                        data.content.copyClipboard(context)
                                        if (data.img != null && data.img.size > 0) {
//                                            ImageUtils.saveImageToExternalStorage(data.img[0])
                                            ImageLoader.getInstance().downloadPic(mContext, data.img)
                                            "保存成功".showToast()
                                        }
                                    }
                            } else {
                                if (mCustomDialog == null) {
                                    mCustomDialog = CustomDialog1(mContext,
                                        CustomDialog1.OnCloseListener {
                                            AllUtils.requestPermission(mContext as BaseActivity<*>, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                                Manifest.permission.READ_EXTERNAL_STORAGE)
                                                .subscribe { aBoolean ->
//                                        data.content.copyClipboard(context)
                                                    if (data.img != null && data.img.size > 0) {
                                                        ImageLoader.getInstance().downloadPic(mContext, data.img)
                                                        "保存成功".showToast()
                                                    }
                                                }
                                        })
                                }
                                mCustomDialog?.setContent(sb.toString())
                                mCustomDialog?.show()
                            }




                        }
                        Type.MaterialType.TextVideo -> {
//                            data.content.copyClipboard(context)

                            val permissions = arrayOf(
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                            )
                            var sb: StringBuilder? = null
                            for (permission in permissions) {
                                if (ActivityCompat.checkSelfPermission(
                                        mContext,
                                        permission!!
                                    ) != PackageManager.PERMISSION_GRANTED
                                ) {
                                    if (sb == null) {
                                        sb = StringBuilder()
                                    }
                                    val str = AllUtils.permissionTipMap(permission)
                                    if (sb.indexOf(str) == -1) {
                                        if (!TextUtils.isEmpty(sb)) {
                                            sb.append("\n\n")
                                        }
                                        sb.append(str)
                                    }
                                }
                            }
                            if (sb == null || TextUtils.isEmpty(sb)) {
                                data.video.saveVideo(mContext as BaseActivity<*>)
                            } else {
                                if (mCustomDialog == null) {
                                    mCustomDialog = CustomDialog1(mContext,
                                        CustomDialog1.OnCloseListener {
                                            data.video.saveVideo(mContext as BaseActivity<*>)
                                        })
                                }
                                mCustomDialog?.setContent(sb.toString())
                                mCustomDialog?.show()
                            }

                        }
                    }
                }
            }
            shareDialog.dismiss()
        }
        shareDialog.showSavePic(info.viewType != Type.MaterialType.Text)
        shareDialog.show()
    }
}